<template>
  <div>
    <h2>权限管理</h2>
    <el-form ref="addRoleForm" :model="addRoleFormData" label-width="80px">
      <el-form-item label="角色名称">
        <el-input v-model="addRoleFormData.roleName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addRole">添加角色</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="roleList" style="width: 100%">
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <el-table-column label="权限分配">
        <template #default="scope">
          <el-checkbox-group v-model="scope.row.permissions">
            <el-checkbox v-for="permission in allPermissions" :label="permission" :key="permission">{{ permission }}</el-checkbox>
          </el-checkbox-group>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" @click="savePermissions(scope.row)">保存权限</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElForm } from 'element-plus';

// 假设这是所有权限的列表，实际情况可从后端获取
const allPermissions = ref([
  '创建订单',
  '编辑订单',
  '删除订单',
  '视图报告',
  '批准订单'
]);

// 角色列表数据
const roleList = ref([
  {
    roleId: 1,
    roleName: '销售经理',
    permissions: ['createOrder', 'editOrder', 'viewReport', 'approveOrder']
  },
  {
    roleId: 2,
    roleName: '销售人员',
    permissions: ['createOrder', 'editOrder']
  }
]);

// 新增角色的表单数据
const addRoleFormData = ref({
  roleName: ''
});

// 获取角色列表及初始权限信息（这里只是模拟数据，实际应调用后端接口）
const getRoleList = async () => {
  // 模拟延迟获取数据
  setTimeout(() => {
    roleList.value = [
      {
        roleId: 1,
        roleName: '销售经理',
        permissions: ['createOrder', 'editOrder', 'viewReport', 'approveOrder']
      },
      {
        roleId: 2,
        roleName: '销售人员',
        permissions: ['createOrder', 'editOrder']
      }
    ];
  }, 1000);
};

// 保存角色权限（这里只是模拟数据更新，实际应调用后端接口）
const savePermissions = (role) => {
  const index = roleList.value.findIndex(r => r.roleId === role.roleId);
  if (index > -1) {
    roleList.value[index].permissions = role.permissions;
    ElMessage.success('权限保存成功');
  } else {
    ElMessage.error('权限保存失败');
  }
};

// 添加角色
const addRole = () => {
  const { roleName } = addRoleFormData.value;
  if (roleName) {
    // 这里只是简单模拟生成角色 ID，实际应由后端生成
    const newRoleId = roleList.value.length + 1;
    roleList.value.push({
      roleId: newRoleId,
      roleName,
      permissions: []
    });
    // 清空表单数据
    addRoleFormData.value.roleName = '';
    ElMessage.success('角色添加成功');
  } else {
    ElMessage.warning('请输入角色名称');
  }
};

onMounted(() => {
  getRoleList();
});
</script>

<style scoped>

</style>
